package com.jsits.v2x.common.connection.ftp;

import com.jsits.v2x.common.util.ZipUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Date;

public class FtpClient extends FtpBase
{
	/*
	 * FTP连接客户端
	 */
	private FTPClient ftpClient;
	
	/*
	 * 日志
	 */
	private final static Logger logger = LoggerFactory.getLogger(FtpClient.class);
	
	/*
	 * 建立FTP连接
	 * @see com.jsits.connection.ftp.FTPBase#connectServer()
	 */
	protected boolean connectServer() 
	{
		ftpClient = new FTPClient();
		
		//设置FTP连接属性
		ftpClient.setConnectTimeout(serverInfo.getConnectTimeout());
		//ftpClient.setDataTimeout(serverInfo.getReadTimeout());
		
		try
		{
			ftpClient.connect(serverInfo.getIp(), serverInfo.getPort());
			ftpClient.login(serverInfo.getUserName(), serverInfo.getPassword());
			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) 
			{
                throw new Exception();  
            } 
			
			ftpClient.setControlEncoding("UTF-8");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
            ftpClient.enterLocalPassiveMode();
            
			if (!StringUtils.equals(serverInfo.getRemotePath().trim(), "")) 
			{
				ftpClient.changeWorkingDirectory(serverInfo.getRemotePath());
			}
			
			if (!StringUtils.equals(serverInfo.getLocalPath(), "")) 
			{
				File localDirectory = new File(serverInfo.getLocalPath());
				if (!localDirectory.exists() || !localDirectory.isDirectory()) 
				{
					localDirectory.mkdirs();
				}
			}
		} 
		catch (Exception e) 
		{
			disConnectServer();
			logger.error("Connect ftp server: " + serverInfo.getIp() + " failed");
			return false;
		}
		
		serverInfo.setStatus(true);
		serverInfo.setTimeStamp(new Date().getTime());
		
		logger.info("Connect ftp server: " + serverInfo.getIp() + " success");
		
		return true;
	}
	
	/*
	 * 断开FTP连接
	 * @see com.jsits.connection.ftp.FTPBase#disConnectServer()
	 */
	protected void disConnectServer() 
	{
		try 
		{
			ftpClient.disconnect();
		}
		catch (IOException e) 
		{
			logger.error(e.getMessage());
		}
	}
	
	/*
	 * 从FTP服务端获取文件
	 */
	public String getFileFromServer(String fileName) 
	{
		if (!serverInfo.isStatus()) 
		{
			return "";
		}
		
		InputStream in = null;
		InputStreamReader input = null;
		BufferedReader stream = null;
		StringBuilder sb = new StringBuilder();
		try 
		{
			in = ftpClient.retrieveFileStream(fileName);
			input = new InputStreamReader(in);
			stream = new BufferedReader(input);
			String line = stream.readLine();
			while(line != null) 
			{
				sb.append(line).append("\n");
				line = stream.readLine();
			}
			ftpClient.getReply();
			
			//更新时间戳
			serverInfo.setTimeStamp(new Date().getTime());
			
			//保存文件至本地
			if (!StringUtils.equals(serverInfo.getLocalPath(), "")) 
			{
				String directory = serverInfo.getLocalPath() + fileName.substring(8, 16) + "/";
				File file = new File(directory);
				if (!file.exists() || !file.isDirectory()) 
				{
					file.mkdirs();
				}
				
				fileName = directory + fileName;
				ZipUtil.saveFile(fileName, sb.toString());
			}
		}
		catch (Exception e) 
		{
			logger.error("Download ftp data failed");
		}
		finally
		{
			try 
			{
				if (stream != null) 
				{
					stream.close();
				}
			} 
			catch (IOException e) 
			{
			} 
			finally 
			{
				try 
				{
					if (input != null) 
					{
						input.close();
					}
				} 
				catch (IOException e) 
				{
				}
				finally 
				{
					try 
					{
						if (in != null) 
						{
							in.close();
						}
					}
					catch (IOException e) 
					{
					}
				}
			}
		}
		return sb.toString();
	}
	
	public FTPClient getFtpClient()
	{
		return ftpClient;
	}
	
}
